﻿using Prism.Commands;
using Prism.Modularity;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using PrismMetroSample.Infrastructure.Constants;
using PrismMetroSample.MedicineModule.Views;
using PrismMetroSample.PatientModule.Views;
using PrismMetroSample.Shell.Views.RegionAdapterViews;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MahApps.Metro.Controls;
using PrismMetroSample.Infrastructure.Behaviors;
using PrismMetroSample.Infrastructure.Models;
using PrismMetroSample.Infrastructure.Utility;
using PrismMetroSample.Shell.Aop;
using PrismMetroSample.Shell.Views.Dialogs;
using ValidationResult = System.ComponentModel.DataAnnotations.ValidationResult;

namespace PrismMetroSample.Shell.ViewModels
{
    public class MainWindowViewModel : NotificationObject
    {
        #region Fields

        private IModuleManager _moduleManager;
        private readonly IDialogService _dialogService;
        private readonly IDoWork _dowork;
        private IRegion _paientListRegion;
        private IRegion _medicineListRegion;
        private PatientList _patientListView;
        private MedicineMainContent _medicineMainContentView;
        private readonly IRegionManager _regionManager;

        #endregion

        #region Properties

        public IRegionManager RegionMannager { get; }

        private bool _isCanExcute = false;
        public bool IsCanExcute
        {
            get { return _isCanExcute; }
            set { SetProperty(ref _isCanExcute, value); }
        }

        private Brush _bgBrush = Brushes.Aqua;
        public Brush BgBrush
        {
            get { return _bgBrush; }
            set
            {
                SetProperty(ref _bgBrush, value);
            }
        }

        private ObservableCollection<MenuModel> _menuModels;
        public ObservableCollection<MenuModel> MenuModels
        {
            get { return _menuModels; }
            set { SetProperty(ref _menuModels, value); }
        }

        private ObservableCollection<string> _langs;
        public ObservableCollection<string> Langs
        {
            get { return _langs; }
            set { SetProperty(ref _langs, value); }
        }


        private string _helloKey;
        public string HelloKey
        {
            get { return _helloKey; }
            set { SetProperty(ref _helloKey, value); }
        }

        private string _integerGreater10Property;
        [MyRequired(ErrorMessage = "不能为空！")]
        [MyStringLength(18, ErrorMessage = "不到 18 岁不能注册，并请填写合适范围的值", MinimumLength = 3)]
        public string IntegerGreater10Property
        {
            get { return _integerGreater10Property; }
            set { SetProperty(ref _integerGreater10Property, value); }
        }


        private Dictionary<int, Student> _dics;
        public Dictionary<int, Student> Dics
        {
            get { return _dics; }
            set
            {
                SetProperty(ref _dics, value);
            }
        }

        public class Student
        {
            public string Name { get; set; }
        }

        #endregion

        #region Commands

        private DelegateCommand _loadingCommand;
        public DelegateCommand LoadingCommand =>
            _loadingCommand ?? (_loadingCommand = new DelegateCommand(ExecuteLoadingCommand));

        private DelegateCommand _activePaientListCommand;
        public DelegateCommand ActivePaientListCommand =>
            _activePaientListCommand ?? (_activePaientListCommand = new DelegateCommand(ExecuteActivePaientListCommand));

        private DelegateCommand _deactivePaientListCommand;
        public DelegateCommand DeactivePaientListCommand =>
            _deactivePaientListCommand ?? (_deactivePaientListCommand = new DelegateCommand(ExecuteDeactivePaientListCommand));

        private DelegateCommand _activeMedicineListCommand;
        public DelegateCommand ActiveMedicineListCommand =>
            _activeMedicineListCommand ?? (_activeMedicineListCommand = new DelegateCommand(ExecuteActiveMedicineListCommand).ObservesCanExecute(() => IsCanExcute));

        private DelegateCommand _deactiveMedicineListCommand;
        public DelegateCommand DeactiveMedicineListCommand =>
            _deactiveMedicineListCommand ?? (_deactiveMedicineListCommand = new DelegateCommand(ExecuteDeactiveMedicineListCommand).ObservesCanExecute(() => IsCanExcute));


        private DelegateCommand _loadMedicineModuleCommand;
        public DelegateCommand LoadMedicineModuleCommand =>
            _loadMedicineModuleCommand ?? (_loadMedicineModuleCommand = new DelegateCommand(ExecuteLoadMedicineModuleCommand));

        private DelegateCommand<MenuModel> _menuCommand;
        public DelegateCommand<MenuModel> MenuCommand =>
            _menuCommand ?? (_menuCommand = new DelegateCommand<MenuModel>(ExecuteMenuCommand));


        private DelegateCommand<string> _selectionChangedCommand;
        public DelegateCommand<string> SelectionChangedCommand =>
            _selectionChangedCommand ?? (_selectionChangedCommand = new DelegateCommand<string>(ExecuteSelectionChangedCommand));

        private DelegateCommand _showMessageCommand;
        public DelegateCommand ShowMessageCommand =>
            _showMessageCommand ?? (_showMessageCommand = new DelegateCommand(ExecuteShowMessageCommandCommand));


        private DelegateCommand _validateCommand;
        public DelegateCommand ValidateCommand =>
            _validateCommand ?? (_validateCommand = new DelegateCommand(() =>
            {
                BgBrush = Brushes.Red;

            }).ObservesCanExecute(() => IsValid));

        private DelegateCommand _newWindowCommand;
        public DelegateCommand NewWindowCommand =>
            _newWindowCommand ?? (_newWindowCommand = new DelegateCommand(ExecuteNewWindowCommandCommand));

        private DelegateCommand<Brush> _pickBackgroundColorCommand;
        public DelegateCommand<Brush> PickBackgroundColorCommand =>
            _pickBackgroundColorCommand ?? (_pickBackgroundColorCommand = new DelegateCommand<Brush>(ExecutePickBackgroundColorCommand));


        #endregion

        #region  Excutes

        [DmoLogCallHandler]
        public virtual void ExecuteShowMessageCommandCommand()
        {
            var msg = ResourceHelper.GetValue("Info_CodeBehind");

            MessageBox.Show(msg);
        }

        void ExecuteNewWindowCommandCommand()
        {
            _dialogService.ShowDialog(nameof(WindowTestView), new DialogParameters("?id=" + new Random().Next()), CloseWindowEventHandler);
        }

        void ExecuteSelectionChangedCommand(string lang)
        {
            ResourceHelper.LoadResource(lang);
        }

        void ExecuteMenuCommand(MenuModel menu)
        {
            MessageBox.Show(menu.Title);
        }

        void ExecutePickBackgroundColorCommand(Brush brush)
        {
            using (var colorDialog = new System.Windows.Forms.ColorDialog())
            {
                colorDialog.FullOpen = true;

                Color color = ((SolidColorBrush)brush).Color;
                colorDialog.Color = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);

                if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    byte A = colorDialog.Color.A;
                    byte R = colorDialog.Color.R;
                    byte G = colorDialog.Color.G;
                    byte B = colorDialog.Color.B;
                    //var RGB = new[] { R, G, B };
                    //var hex = "#";

                    //for (int i = 0; i < RGB.Length; i++)
                    //{
                    //    hex += RGB[i].ToString("X2");
                    //}

                    Color mediaColor = Color.FromArgb(A, R, G, B);
                    BgBrush = new SolidColorBrush(mediaColor);
                }
            }
        }

        void ExecuteLoadingCommand()
        {
            // 资源动态绑定 需要放在加载事件中赋值 等待资源都加载完毕
            HelloKey = "MainWindow_HelloWorld";

            _paientListRegion = RegionMannager.Regions[RegionNames.PatientListRegion];
            //_patientListView = CommonServiceLocator.ServiceLocator.Current.GetInstance<PatientList>();
            //_paientListRegion.Add(_patientListView);

            var uniformContentRegion = RegionMannager.Regions["UniformContentRegion"];
            var regionAdapterView1 = CommonServiceLocator.ServiceLocator.Current.GetInstance<RegionAdapterView1>();
            uniformContentRegion.Add(regionAdapterView1);
            var btnButton = new Button();
            btnButton.Command = ActivePaientListCommand;
            uniformContentRegion.Add(btnButton);
            var regionAdapterView2 = CommonServiceLocator.ServiceLocator.Current.GetInstance<RegionAdapterView2>();
            uniformContentRegion.Add(regionAdapterView2);

            _medicineListRegion = RegionMannager.Regions[RegionNames.MedicineMainContentRegion];
        }


        void ExecuteDeactiveMedicineListCommand()
        {
            _dialogService.ShowDialog(nameof(WindowTestView), new DialogParameters(), CloseWindowEventHandler);

            _medicineListRegion.Deactivate(_medicineMainContentView);
        }

        private void CloseWindowEventHandler(IDialogResult dialogResult)
        {
            ;
        }

        void ExecuteActiveMedicineListCommand()
        {
            _regionManager.RequestNavigate(RegionNames.DialogPopupRegion, "ModuleAPopup");
            _medicineListRegion.Activate(_medicineMainContentView);
        }

        void ExecuteLoadMedicineModuleCommand()
        {
            _moduleManager.LoadModule("MedicineModule");
            _medicineMainContentView = (MedicineMainContent)_medicineListRegion.Views.Where(t => t.GetType() == typeof(MedicineMainContent)).FirstOrDefault();
            this.IsCanExcute = true;
        }

        void ExecuteDeactivePaientListCommand()
        {
            _regionManager.RequestNavigate("PatientListRegion", "LoginMainContent");
            //_paientListRegion.Deactivate(_patientListView);
        }

        void ExecuteActivePaientListCommand()
        {
            _regionManager.RequestNavigate("PatientListRegion", "PatientList");
            //_paientListRegion.Activate(_patientListView);
        }

        #endregion

        #region - C.tor -

        public MainWindowViewModel(IModuleManager moduleManager, IRegionManager regionManager, IDialogService dialogService, IDoWork dowork)
        {
            _moduleManager = moduleManager;
            _regionManager = regionManager;
            RegionMannager = regionManager;
            _dialogService = dialogService;
            _dowork = dowork;
            //_moduleManager.LoadModuleCompleted += _moduleManager_LoadModuleCompleted;

            _dowork.Display();
            //Dics = new Dictionary<int, Student>() { { 0, new Student() { Name = "123" } } };

            MenuModels = new ObservableCollection<MenuModel>();
            MenuModels.Add(new MenuModel() { IconFont = "\xe602", Title = "Dashboard", });
            MenuModels.Add(new MenuModel() { IconFont = "\xe647", Title = "Apps", });
            MenuModels.Add(new MenuModel() { IconFont = "\xe6a5", Title = "Pages", });
            MenuModels.Add(new MenuModel() { IconFont = "\xe623", Title = "UI Kit", });
            MenuModels.Add(new MenuModel() { IconFont = "\xe649", Title = "Forms", });

            Langs = new ObservableCollection<string>(new List<string> { "zh-CN", "en-US", "de-DE" });
            ResourceHelper.LoadResource("en-US");
        }


        #endregion

        private void _moduleManager_LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e)
        {
            _dialogService.ShowDialog("SuccessDialog", new DialogParameters($"message={e.ModuleInfo.ModuleName + "模块被加载了"}"), null);
        }


    }
}
